package dse.messages.singleversion;

import dse.*;
import dse.messages.*;

public class RequestLockResponseMessageHandler extends MessageSender implements
		MessageHandler {
	private DataRequest request;
	private boolean success;
	private LockProcessor processor;
	
	public RequestLockResponseMessageHandler(Experiment experiment, DataRequest dr, boolean success, LockProcessor lp){
		super(experiment);
		this.request = dr;
		this.success = success;
		this.processor = lp;
	}

	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double currentTime) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgIntrpt: " + message, currentTime);
		//processor.lockProcess(false, message.from(), recorder, currentTime);
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message,
			double currentTime) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgRcvd: " + message, currentTime);
		if (message.messageType() != MessageType.RequestLockResponse) {
			recorder.warn(
					"RequestLockResponseMessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}
		if(message.to().id() == request.getClientID())
			processor.lockProcess(success, message.from(), recorder, currentTime);
		else{
			Node receiver = message.to();
			if(request.isFollowerReady()){
				Message m = super.createRequestLockResponseMessage(receiver, processor.getRequester(), request, request.isGranted(), message.purpose(), processor);
				//recorder.debug(this, "new msg: " + m, currentTime);
				experiment.messageQueue().enqueueMessage(m, currentTime);
			}
			else{
				boolean r = receiver.receiveLeaderDecision(request);
				if(r && request.isGranted()){
					Message m = super.createRequestLockResponseMessage(receiver, processor.getRequester(), request, true, message.purpose(), processor);
					//recorder.debug(this, "new msg: " + m, currentTime);
					experiment.messageQueue().enqueueMessage(m, currentTime);
				}
			}
		}
	}

}
